<template>
  <div class="comment">
    <h3>发表评论</h3>
    <hr />
    <textarea placeholder="请输入评论内容(最多评论100字)" maxlength="100" v-model="msg"></textarea>

    <mt-button type="primary" size="large" @click="postword">发表评论</mt-button>

    <div class="content-list">
      <div class="content-item" v-for="(item,index) in contentlist" :key="item.url">
        <div
          class="content-title"
        >第{{index+1}}楼&nbsp;&nbsp;用户：匿名用户:{{item.user_name}}&nbsp;&nbsp;发表时间:{{item.add_time|dataFormat}}</div>
        <div class="content-body">{{item.content}}</div>
      </div>
      <div class="content-item">
        <div class="content-title">第一楼&nbsp;&nbsp;用户：匿名用户&nbsp;&nbsp;发表时间:2019-10-05 12:12:12</div>
        <div class="content-body">这新闻真实</div>
      </div>
      <div class="content-item">
        <div class="content-title">第二楼&nbsp;&nbsp;用户：匿名用户&nbsp;&nbsp;发表时间:2019-10-05 12:12:12</div>
        <div class="content-body">这新闻不错</div>
      </div>
    </div>

    <mt-button type="danger" size="large" plain @click="getmore">加载更多</mt-button>
  </div>
</template>
<script>
import { Toast } from "mint-ui";
export default {
  data() {
    return {
      pageindex: 1,
      contentlist: {},
      msg: ""
    };
  },
  created() {
    this.getcontent();
  },
  methods: {
    getcontent() {
      this.$http
        .get("api/getcomments/" + this.id + "?pageindex=" + this.pageindex)
        .then(result => {
          if (result.body.status == 0) {
            this.contentlist = this.contentlist.concat(result.body.message);
          } else {
            Toast("评论加载失败");
          }
        });
    },
    getmore() {
      this.pageindex++;
      this.getcontent();
    }, //发表评论
    postword() {
      if (this.msg.trim().length === 0) {
        return Toast("评论内容不能为空");
      }

      // 参数一：请求的url地址
      // 参数二：提交给服务器的对象{content:this.msg}
      // 参数三：定义提交的时候，表单中的数据格式{emulateJSON:true}
      this.$http
        .post("api/postcomment/" + this.$route.params.id, {
          content: this.msg.trim()
        })
        .then(function(dataStr) {
          if (dataStr.body.message == 0) {
            var cmt = {
              user_name: "匿名用户",
              add_time: Date.now(),
              content: this.msg.trim()
            };
            this.contentlist.unshift(cmt);
            this.msg=""
          }
        });
    }
  },
  props: ["id"]
};
</script>

<style lang="scss" scoped>
.comment {
  h1 {
    font-size: 18px;
  }
  textarea {
    font-size: 14px;
    height: 85px;
    margin: 0;
  }
  .content-list {
    margin: 6px 0;
    .content-item {
      font-size: 13px;
      .content-title {
        background-color: #ccc;
        line-height: 36px;
      }
    }
    .content-body {
      line-height: 36px;
      text-indent: 2em;
    }
  }
}
</style>